package com.yitongmao.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.bean.Guanzhu;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.MyBean;
import com.yitongmao.bean.ShoppingNumBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.dialog.CommomDialog;
import com.yitongmao.util.DipUtils;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.util.X5WebView;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;

public class ShoppingDatailsActivity extends AppCompatActivity {
    @Bind(R.id.mRedaihuitui)
    AutoLinearLayout mRedaihuitui;
    @Bind(R.id.mAttention)
    AutoLinearLayout mAttention;
    @Bind(R.id.mTextShoppingNum)
    TextView mTextShoppingNum;
    @Bind(R.id.mService)
    AutoLinearLayout mService;
    @Bind(R.id.mAddShopping)
    Button mAddShopping;
    private String shoppingId;
    private String userId;
    private LoginHuancunBean loginHuancunBean;
    private X5WebView mWebview;
    private int loginId1;
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    private String number = "4000114888";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immerSion();
        setContentView(R.layout.activity_shopping_datails);
        Gson gson = new Gson();
        String loginId = ACache.get(ShoppingDatailsActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            loginId1 = loginHuancunBean.userInfo.loginId;
            String userId = String.valueOf(loginHuancunBean.userInfo.id);
            getShoppingNum(userId);
        }
        ButterKnife.bind(this);
        initView();
        addShopping();
    }
    private void addShopping() {
        mAddShopping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Gson gson=new Gson();
                String loginId = ACache.get(ShoppingDatailsActivity.this).getAsString("loginId");
                if (loginId!=null){
                    loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
                    int userId = loginHuancunBean.userInfo.id;
                    loginId1 = loginHuancunBean.userInfo.loginId;

                    addShopping(String.valueOf(userId),shoppingId,"2");
                }else {
                    Intent intent=new Intent(ShoppingDatailsActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    private void initView() {
        mWebview = (X5WebView) findViewById(R.id.mWebview);
        mWebview.setWebViewClient(new WebViewClient());
        mWebview.setWebChromeClient(new WebChromeClient());
        Intent intent = getIntent();
        shoppingId = intent.getStringExtra("shoppingId");
        userId = intent.getStringExtra("userId");
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        //解析查找的缓存并判断
        Gson gson = new Gson();
        String loginId = ACache.get(ShoppingDatailsActivity.this).getAsString("loginId");
        if (loginId != null) {
            loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
            int id = loginHuancunBean.userInfo.id;
            loginId1 = loginHuancunBean.userInfo.loginId;
            mWebview.loadUrl(AppConstancts.Net.shoppingDtailsUrl + "?id=" + shoppingId + "&loginId=" + loginId1 + "&signLogin=" + SignUtil.signLogin(nonce, timestamp) + "&timestamp=" + timestamp + "&nonce=" + nonce);
            userId = String.valueOf(id);
        } else {
            mWebview.loadUrl(AppConstancts.Net.shoppingDtailsUrl + "?id=" + shoppingId);
        }
        AutoLinearLayout shopping_AutoRelativeLayout = (AutoLinearLayout) findViewById(R.id.shopping_AutoRelativeLayout);
        shopping_AutoRelativeLayout.setPadding(0, 0, 0, DipUtils.getBottomStatusHeight(this));
        mRedaihuitui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShoppingDatailsActivity.this.finish();
            }
        });
        mAttention.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加关注
                setNetWork(userId, shoppingId);
            }
        });
        mService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                if (ContextCompat.checkSelfPermission(ShoppingDatailsActivity.this, Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    ActivityCompat.requestPermissions(ShoppingDatailsActivity.this, new String[]{Manifest.permission.CALL_PHONE},
                            WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                } else {
                    new CommomDialog(ShoppingDatailsActivity.this, R.style.dialog, " ", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            Intent intentOne = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
                            if (ActivityCompat.checkSelfPermission(ShoppingDatailsActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                return;
                            }
                            startActivity(intentOne);
                        }
                    }).setTitle("是否拨打400-011-4888？").show();
                }
            }
        });

    }
    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }
    //添加关注
    public void setNetWork(String userId, String shoppingId) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("goodsId", shoppingId);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.addAttentionUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Gson gson = new Gson();
                Guanzhu guanzhu = gson.fromJson(string, Guanzhu.class);
                ToastUtils.showShort(ShoppingDatailsActivity.this, "" + guanzhu.result.message);
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }
    //购物车数量
    public void getShoppingNum(String userId) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId", userId);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.getShoppingNumUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                Log.e("zzz", result.toString());
                String string = (String) result;
                Gson gson = new Gson();
                ShoppingNumBean shoppingNumBean = gson.fromJson(string, ShoppingNumBean.class);
                if (shoppingNumBean.result.state.equals("1")) {
                    mTextShoppingNum.setText(shoppingNumBean.number + "");
                }
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }
    //加入购物车
    public void addShopping(final String userId, String goodsId , String num) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("userId",userId);
        params.put("goodsId",goodsId);
        params.put("num",num);
        params.put("spec","0");
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("signLogin", SignUtil.signLogin(nonce, timestamp));
        params.put("loginId", String.valueOf(loginId1));
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.addShoppingUrl, params, new CallBackListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(Object result) {
                Log.e("onSuccess",result.toString());
                String string = (String) result;
                Gson gson = new Gson();
                MyBean myBean = gson.fromJson(string, MyBean.class);
                if (myBean.result.state.equals("1")){
                    ToastUtils.showShort(ShoppingDatailsActivity.this,"添加成功");
                    getShoppingNum(userId);
                }else {
                    ToastUtils.showShort(ShoppingDatailsActivity.this,""+myBean.result.message);
                }
            }
            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }
}
